<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 人数最多的站点（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>公园园区提供小火车单向通行&#xff0c;从园区站点编号最小到最大通行如1~2~3~4~1&#xff0c;然后供员工在各个办公园区穿梭&#xff0c;通过对公司N个员工调研统计到每个员工的坐车区间&#xff0c;包含前后站点&#xff0c;请设计一个程序计算出小火车在哪个园区站点时人数最多。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第1个行&#xff0c;为调研员工人数</p> 
<p>第2行开始&#xff0c;为每个员工的上车站点和下车站点。<br /> 使用数字代替每个园区用空格分割&#xff0c;如3 5表示从第3个园区上车&#xff0c;在第5个园区下车</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>人数最多时的园区站点编号&#xff0c;最多人数相同时返回编号最小的园区站点</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">3<br /> 1 3<br /> 2 4<br /> 1 4</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题其实就是求解最大重叠区间个数的变种题。</p> 
<p>即&#xff0c;我们只要找到具有最大重叠部分的区间的起点就是本题题解。</p> 
<p>关于最大重叠区间个数求解&#xff0c;请看<a href="https://www.bilibili.com/video/BV1nq4y1B7Mm/?vd_source&#61;b5105a99a0628dd906e154263279c518" rel="nofollow" title="年年岁岁都容易挂的算法高频面试题&#xff0c;一线大厂经典面试题之堆和最大线段重合问题_哔哩哔哩_bilibili">年年岁岁都容易挂的算法高频面试题&#xff0c;一线大厂经典面试题之堆和最大线段重合问题_哔哩哔哩_bilibili</a></p> 
<p>上面视频的核心思想其实就是&#xff1a;</p> 
<ul><li>首先&#xff0c;将所有区间按开始位置升序</li><li>然后&#xff0c;遍历排序后区间&#xff0c;并将小顶堆中小于遍历区间起始位置的区间弹出&#xff08;小顶堆实际存储区间结束位置&#xff09;&#xff0c;此操作后&#xff0c;小顶堆中剩余的区间个数&#xff0c;就是和当前遍历区间重叠数。</li></ul> 
<p>我们只需要在求解最大重叠数时&#xff0c;保留遍历的区间的起始位置即可。</p> 
<p>对于JS而言&#xff0c;没有原生堆结构&#xff08;即优先队列&#xff09;&#xff0c;因此我们需要手写小顶堆代码&#xff0c;关于优先队列&#xff0c;大家可以参考&#xff1a;</p> 
<p><a href="https://blog.csdn.net/qfc_128220/article/details/127695013" title="LeetCode - 1705 吃苹果的最大数目_伏城之外的博客-CSDN博客">LeetCode - 1705 吃苹果的最大数目_伏城之外的博客-CSDN博客</a></p> 
<p>但是本题是100分值的&#xff0c;可能不会存在大数量级&#xff0c;因此大家可以先尝试用有序数组代替小顶堆&#xff0c;如果不行&#xff0c;再实现小顶堆。</p> 
<p></p> 
<p>另外&#xff0c;本题和<a href="https://fcqian.blog.csdn.net/article/details/128192516" rel="nofollow" title="华为OD机试 - 最大化控制资源成本_伏城之外的博客-CSDN博客">华为OD机试 - 最大化控制资源成本_伏城之外的博客-CSDN博客</a></p> 
<p>很像&#xff0c;大家可以继续尝试做下上面这题。</p> 
<p></p> 
<p>2023.2.1根据网友指正&#xff0c;本题小火车是有可能走回程的&#xff0c;比如&#xff0c;坐车区间 为 [3,2]&#xff0c;即从站点3 -&gt; 站点4 -&gt; 站点1 -&gt; 站点2。</p> 
<p>对于这种情况&#xff0c;就会破坏上面对于区间的排序。因此&#xff0c;我们需要将&#xff1a;该情况的坐车区间拆分为 [3, 4]和[1, 2]</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    const ranges &#61; lines.slice(1).map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));
    console.log(getResult(ranges));
    lines.length &#61; 0;
  }
});

function getResult(ranges) {
  // 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
  const last &#61; Math.max.apply(null, ranges.toString().split(&#34;,&#34;).map(Number));

  // 如果存在 [3,2] 这种坐车区间&#xff0c;即从站点3 -&gt; 站点4 -&gt; 站点1 -&gt; 站点2&#xff0c;则此时将该坐车区间拆分为 [3, 4]和[1, 2]
  const tmp &#61; [];
  ranges.forEach((range) &#61;&gt; {
    const [s, e] &#61; range;

    if (s &gt; e) {
      // 拆分
      tmp.push([s, last]);
      tmp.push([1, e]);
    } else {
      tmp.push(range);
    }
  });
  ranges &#61; tmp;

  // 最大重叠区间个数求解
  ranges.sort((a, b) &#61;&gt; a[0] - b[0]);
  const end &#61; new PriorityQueue((a, b) &#61;&gt; b - a);

  let max &#61; 0;
  let ans &#61; ranges[0][0];
  for (let range of ranges) {
    const [s, e] &#61; range;

    while (end.size()) {
      const top &#61; end.peek();

      if (top &lt; s) {
        end.shift();
      } else {
        break;
      }
    }

    end.push(e);

    if (end.size() &gt; max) {
      max &#61; end.size();
      ans &#61; s;
    }
  }

  return ans;
}

class PriorityQueue {
  constructor(cpr) {
    this.queue &#61; [];
    this.cpr &#61; cpr;
  }

  swap(a, b) {
    const tmp &#61; this.queue[a];
    this.queue[a] &#61; this.queue[b];
    this.queue[b] &#61; tmp;
  }

  // 上浮
  swim() {
    let c &#61; this.queue.length - 1;

    while (c &gt;&#61; 1) {
      const f &#61; Math.floor((c - 1) / 2);

      if (this.cpr(this.queue[c], this.queue[f]) &gt; 0) {
        this.swap(c, f);
        c &#61; f;
      } else {
        break;
      }
    }
  }

  // 入队
  push(val) {
    this.queue.push(val);
    this.swim();
  }

  // 下沉
  sink() {
    let f &#61; 0;

    while (true) {
      let c1 &#61; 2 * f &#43; 1;
      let c2 &#61; c1 &#43; 1;

      let c;
      let val1 &#61; this.queue[c1];
      let val2 &#61; this.queue[c2];
      if (val1 &amp;&amp; val2) {
        c &#61; this.cpr(val1, val2) &gt; 0 ? c1 : c2;
      } else if (val1 &amp;&amp; !val2) {
        c &#61; c1;
      } else if (!val1 &amp;&amp; val2) {
        c &#61; c2;
      } else {
        break;
      }

      if (this.cpr(this.queue[c], this.queue[f]) &gt; 0) {
        this.swap(c, f);
        f &#61; c;
      } else {
        break;
      }
    }
  }

  // 出队
  shift() {
    this.swap(0, this.queue.length - 1);
    const res &#61; this.queue.pop();
    this.sink();
    return res;
  }

  // 查看顶
  peek() {
    return this.queue[0];
  }

  size() {
    return this.queue.length;
  }
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[][] ranges &#61; new int[n][2];

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      ranges[i][0] &#61; sc.nextInt();
      ranges[i][1] &#61; sc.nextInt();
    }

    System.out.println(getResult(ranges));
  }

  public static int getResult(int[][] ranges) {
    // 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
    Integer last &#61;
        Arrays.stream(ranges)
            .map(range -&gt; Math.max(range[0], range[1]))
            .max((a, b) -&gt; a - b)
            .orElse(0);

    // 如果存在 [3,2] 这种坐车区间&#xff0c;即从站点3 -&gt; 站点4 -&gt; 站点1 -&gt; 站点2&#xff0c;则此时将该坐车区间拆分为 [3, 4]和[1, 2]
    ArrayList&lt;Integer[]&gt; tmp &#61; new ArrayList&lt;&gt;();
    for (int[] range : ranges) {
      int s &#61; range[0];
      int e &#61; range[1];

      if (s &gt; e) {
        tmp.add(new Integer[] {s, last});
        tmp.add(new Integer[] {1, e});
      } else {
        tmp.add(new Integer[] {s, e});
      }
    }

    // 最大重叠区间个数求解
    tmp.sort((a, b) -&gt; a[0] - b[0]);

    PriorityQueue&lt;Integer&gt; end &#61; new PriorityQueue&lt;&gt;((a, b) -&gt; a - b);

    int max &#61; 0;
    int ans &#61; tmp.get(0)[0];
    for (Integer[] range : tmp) {
      int s &#61; range[0];
      int e &#61; range[1];

      while (end.size() &gt; 0) {
        Integer top &#61; end.peek();

        if (top &lt; s) {
          end.poll();
        } else {
          break;
        }
      }

      end.offer(e);

      if (end.size() &gt; max) {
        max &#61; end.size();
        ans &#61; s;
      }
    }
    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import queue

# 输入获取
n &#61; int(input())
ranges &#61; [list(map(int, input().split())) for i in range(n)]


# 算法入口
def getResult(ranges):
    # 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
    last &#61; max(map(lambda x: max(x[0], x[1]), ranges))

    # 如果存在 [3,2] 这种坐车区间&#xff0c;即从站点3 -&gt; 站点4 -&gt; 站点1 -&gt; 站点2&#xff0c;则此时将该坐车区间拆分为 [3, 4]和[1, 2]
    tmp &#61; []
    for ran in ranges:
        s, e &#61; ran

        if s &gt; e:
            tmp.append([s, last])
            tmp.append([1, e])
        else:
            tmp.append(ran)
    ranges &#61; tmp

    # 最大重叠区间个数求解
    ranges.sort(key&#61;lambda x: x[0])
    end &#61; queue.PriorityQueue()
    maxV &#61; 0
    ans &#61; ranges[0][0]

    for ran in ranges:
        s, e &#61; ran

        while end.qsize() &gt; 0:
            top &#61; end.queue[0]

            if top &lt; s:
                end.get()
            else:
                break

        end.put(e)

        if end.qsize() &gt; maxV:
            maxV &#61; end.qsize()
            ans &#61; s

    return ans


print(getResult(ranges))
</code></pre> 
<p></p> 
<h3>基于差分数列求解本题&#xff08;更适合本题&#xff09;</h3> 
<p>关于差分数列&#xff0c;请看</p> 
<p><a href="https://blog.csdn.net/qfc_128220/article/details/128976936?spm&#61;1001.2014.3001.5501" title="算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客">算法设计 - 前缀和 &amp; 差分数列_伏城之外的博客-CSDN博客</a></p> 
<p>然后可以尝试下leetcode下面差分数列题目</p> 
<p><a href="https://blog.csdn.net/qfc_128220/article/details/128978132?spm&#61;1001.2014.3001.5501" title="LeetCode - 1109 - 航班预定统计_伏城之外的博客-CSDN博客">LeetCode - 1109 - 航班预定统计_伏城之外的博客-CSDN博客</a></p> 
<p>本题差分数列求解的解析可以参照上面两个博客</p> 
<p></p> 
<h4>JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    const ranges &#61; lines.slice(1).map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));
    console.log(getResult(ranges));
    lines.length &#61; 0;
  }
});

function getResult(ranges) {
  // 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
  const last &#61; Math.max.apply(null, ranges.toString().split(&#34;,&#34;).map(Number));

  const diff &#61; new Array(last).fill(0);

  for (let range of ranges) {
    const [l, r] &#61; range;
    if (l &gt; r) {
      diff[l - 1] &#43;&#61; 1;
      diff[0] &#43;&#61; 1;
      diff[r] -&#61; 1;
    } else {
      diff[l - 1] &#43;&#61; 1;
      if (r &lt; last) diff[r] -&#61; 1;
    }
  }

  const preSum &#61; [diff[0]];
  let max &#61; preSum[0];
  let maxI &#61; 0;
  for (let i &#61; 1; i &lt; last; i&#43;&#43;) {
    preSum[i] &#61; preSum[i - 1] &#43; diff[i];
    if (preSum[i] &gt; max) {
      max &#61; preSum[i];
      maxI &#61; i;
    }
  }

  return maxI &#43; 1;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[][] ranges &#61; new int[n][2];

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      ranges[i][0] &#61; sc.nextInt();
      ranges[i][1] &#61; sc.nextInt();
    }

    System.out.println(getResult(ranges));
  }

  public static int getResult(int[][] ranges) {
    // 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
    int last &#61;
        Arrays.stream(ranges)
            .map(range -&gt; Math.max(range[0], range[1]))
            .max((a, b) -&gt; a - b)
            .orElse(0);

    int[] diff &#61; new int[last];

    for (int[] range : ranges) {
      int l &#61; range[0];
      int r &#61; range[1];

      if (l &gt; r) {
        diff[l - 1] &#43;&#61; 1;
        diff[0] &#43;&#61; 1;
        diff[r] -&#61; 1;
      } else {
        diff[l - 1] &#43;&#61; 1;
        if (r &lt; last) diff[r] -&#61; 1;
      }
    }

    int[] preSum &#61; new int[last];
    int max &#61; preSum[0] &#61; diff[0];
    int maxI &#61; 0;
    for (int i &#61; 1; i &lt; last; i&#43;&#43;) {
      preSum[i] &#61; preSum[i - 1] &#43; diff[i];
      if (preSum[i] &gt; max) {
        max &#61; preSum[i];
        maxI &#61; i;
      }
    }

    return maxI &#43; 1;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
ranges &#61; [list(map(int, input().split())) for i in range(n)]


# 算法入口
def getResult(ranges):
    # 由于题目并未说有几个站点&#xff0c;因此需要计算出最后一个站点
    last &#61; max(map(lambda x: max(x[0], x[1]), ranges))

    diff &#61; [0 for i in range(last)]

    for ran in ranges:
        l, r &#61; ran
        if l &gt; r:
            diff[l - 1] &#43;&#61; 1
            diff[0] &#43;&#61; 1
            diff[r] -&#61; 1
        else:
            diff[l - 1] &#43;&#61; 1
            if r &lt; last:
                diff[r] -&#61; 1

    preSum &#61; [0 for i in range(last)]
    maxV &#61; preSum[0] &#61; diff[0]
    maxI &#61; 0
    for i in range(1, last):
        preSum[i] &#61; preSum[i - 1] &#43; diff[i]
        if preSum[i] &gt; maxV:
            maxV &#61; preSum[i]
            maxI &#61; i

    return maxI &#43; 1


# 算法调用
print(getResult(ranges))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>